package com.jxtc.enterprise.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.jxtc.enterprise.common.utils.ResultCode;
import com.jxtc.enterprise.merchant.dto.FoodUpdateDTO;
import com.jxtc.enterprise.merchant.dto.FoodCreateDTO;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.common.vo.PaginationResponseVO;
import com.jxtc.enterprise.merchant.dto.*;
import com.jxtc.enterprise.merchant.service.MerchantFoodManageService;
import com.jxtc.enterprise.merchant.service.MerchantStoreManageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 编号 21 菜品管理 页面的所有功能对应的接口
 */
@RestController
@RequestMapping("/jxtc/enterprise/merchant/foodManage")
@Slf4j
public class MerchantFoodManageController {

    @Autowired
    private MerchantFoodManageService merchantFoodManageService;

    @Autowired
    private MerchantStoreManageService merchantStoreManageService;


    /**
     * 接口21.1 根据查询条件，返回符合条件的菜品列表； 当前支持的查询条件：菜品名称，状态（上架中或下架中），
     * 适用场景：
     * 1. 首次打开 菜品管理 页面，菜品名空，状态传递 1 上架中，查询菜品列表展示在 上架中 页面
     * 2. 输入菜品名，输入符合条件的菜品列表，搜索框中的条件，仅影响当前打开的tab页，比如当前处于【上架中】页面，搜索框输入 “小炒”返回的结果为：(1) 上架中 页面展示 名称中包含“小炒”的菜品，(2) 下架中 页面展示所有的菜品
     *
     * @param requestBody
     * @return
     */
    @PostMapping("queryFoods")
    public Result<JSONObject> queryFoods(@RequestBody String requestBody) {

        JSONObject resultData = new JSONObject();
        log.info("url: {}, request body: {}", "/jxtc/enterprise/merchant/foodManage/queryFoods", requestBody);
        JSONObject request = JSONObject.parseObject(requestBody);
        String storeId = request.getString("storeId");
        String foodName = request.getString("foodName");
        Integer status = request.getInteger("status");
        String phone = request.getString("phone");
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(phone);
        }

        Integer currentPage = Optional.ofNullable(request.getInteger("currentPage")).orElse(1);
        // 当前小程序页面，没有做分页，分页参数都是空，如果分页参数都为空，则一次返回所有菜品
        Integer pageSize = Optional.ofNullable(request.getInteger("pageSize")).orElse(Integer.MAX_VALUE);

        PaginationResponseVO<JSONObject> vo = merchantFoodManageService.pageFoodByStoreIdFoodNameOrFoodStatus(storeId, foodName, status, currentPage, pageSize);
        // 先查询出各种状态的菜品个数
        JSONObject foodCountOfEachStatus = merchantFoodManageService.queryFoodCountOfEachStatus(storeId, foodName, status);
        resultData.put("onSale", foodCountOfEachStatus.getOrDefault("onSale", 0));
        resultData.put("offSale", foodCountOfEachStatus.getOrDefault("offSale", 0));
        resultData.put("total", vo.getTotal());
        resultData.put("current", vo.getCurrent());
        resultData.put("records", vo.getRecords());

        log.info("response {}", resultData);

        return ResultGenerator.genSuccessResult(resultData);
    }

    /**
     * 接口21.2 新增菜品
     *
     * @param dto
     * @return
     */
    @PostMapping("addNewFood")
    public Result<JSONObject> addNewFood(@Valid @RequestBody FoodCreateDTO dto) {

        log.info("url: /jxtc/enterprise/merchant/addNewFood, request body: {}", dto);

        if (StringUtils.isBlank(dto.getStoreId())) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            String storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
            // 并将查询到的 storeId 回填到 dto 中
            dto.setStoreId(storeId);
        }

        JSONObject vo = merchantFoodManageService.saveFood(dto);

        log.info("response: {}", ResultGenerator.genSuccessResult(vo));

        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 接口21.3 查询店铺中的菜品类别
     *
     * @param storeId
     * @param phone
     * @return
     */
    @GetMapping("queryFoodTypes")
    public Result<List<String>> queryFoodTypes(@RequestParam String storeId, @RequestParam String phone) {

        log.info("url: /jxtc/enterprise/merchant/queryFoodTypes, storeId: {}, phone: {}", storeId, phone);
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(phone);
        }
        String foodTypes = merchantFoodManageService.queryFoodTypesByStoreId(storeId);
        List<String> foodTypeList;
        if (StringUtils.isNotEmpty(foodTypes)) {
            foodTypeList = JSONObject.parseArray(foodTypes).toJavaList(String.class);
        } else {
            foodTypeList = new ArrayList<>();
        }
        log.info("response: {}", ResultGenerator.genSuccessResult(foodTypeList));
        return ResultGenerator.genSuccessResult(foodTypeList);
    }

    /**
     * 接口21.4 查询菜品详情
     *
     * @param storeId
     * @param phone
     * @param foodId
     * @return
     */
    @GetMapping("queryFoodDetail")
    public Result queryFoodDetail(@RequestParam String storeId, @RequestParam String phone, @RequestParam String foodId) {

        String requestId = UUID.randomUUID().toString();
        log.info("requestId: {}, url: /jxtc/enterprise/merchant/foodManage/queryFoodDetail, storeId: {}, phone: {}, foodId: {}",
                requestId, storeId, phone, foodId);
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(phone);
        }
        JSONObject foodVo = merchantFoodManageService.queryFoodDetailByFoodId(storeId, foodId);
        log.info("requestId: {},response: {}",
                requestId, foodVo.toJSONString());
        if (foodVo == null) {
            return ResultGenerator.genFailResult(ResultCode.NOT_FOUND, "菜品id不存在");
        } else {
            return ResultGenerator.genSuccessResult(foodVo);
        }
    }

    /**
     * 接口21.5 编辑菜品信息
     *
     * @param dto
     * @return
     */
    @PostMapping("editFood")
    public Result<JSONObject> editFood(@Valid @RequestBody FoodUpdateDTO dto) {

        log.info("url: /jxtc/enterprise/merchant/foodManage/editFood, request body: {}", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getStoreId())) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            String storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
            // 并将查询到的 storeId 回填到 dto 中
            dto.setStoreId(storeId);
        }
        merchantFoodManageService.updateFoodById(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示上架或下架菜品成功；code 为 400 时，message 字段返回错误提示信息")
    @Operation(summary = "21.6 上架或下架某个菜品", tags = "21. 商铺端菜品管理", operationId = "21.6")
    @PostMapping("/changeFoodStatus")
    public Result<Void> changeFoodStatus(@Valid @RequestBody ChangeFoodStatusDTO dto) {
        String storeId = dto.getStoreId();
        log.info("/changeFoodStatus, storeId: {}, phone: {}, foodId: {}, status: {}", storeId, dto.getPhone(), dto.getFoodId(), dto.getStatus());
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
        }
        merchantFoodManageService.changeFoodStatusByStoreIdAndFoodId(storeId, dto.getFoodId(), dto.getStatus());
        return ResultGenerator.genSuccessResult();
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示软删除菜品成功；code 为 400 时，message 字段返回错误提示信息")
    @Operation(summary = "21.7 软删除菜品", tags = "21. 商铺端菜品管理", operationId = "21.7")
    @PostMapping("/deleteFood")
    public Result<Void> deleteFood(@Valid @RequestBody DeleteFoodDTO dto) {
        String storeId = dto.getStoreId();
        log.info("/deleteFood, storeId: {}, phone: {}, foodId: {}", storeId, dto.getPhone(), dto.getFoodId());
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
        }
        merchantFoodManageService.deleteFoodByStoreIdAndFoodId(storeId, dto.getFoodId());
        return ResultGenerator.genSuccessResult();
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示新增菜品类别成功；code 为 400 时，message 字段返回错误提示信息")
    @Operation(summary = "21.8 新增菜品类别", tags = "21. 商铺端菜品管理", operationId = "21.8")
    @PostMapping("/addNewFoodType")
    public Result<Void> addNewFoodType(@Valid @RequestBody AddNewFoodTypeDTO dto) {
        String storeId = dto.getStoreId();
        log.info("/addNewFoodType, storeId: {}, phone: {}, foodTypeName: {}", storeId, dto.getPhone(), dto.getFoodTypeName());
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
        }
        merchantFoodManageService.addNewFoodTypeByStoreId(storeId, dto.getFoodTypeName());
        return ResultGenerator.genSuccessResult();
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示编辑菜品类别成功；code 为 400 时，message 字段返回错误提示信息")
    @Operation(summary = "21.9 编辑菜品类别", tags = "21. 商铺端菜品管理", operationId = "21.9")
    @PostMapping("/editFoodType")
    public Result<Void> editFoodType(@Valid @RequestBody EditFoodTypeDTO dto) {
        String storeId = dto.getStoreId();
        log.info("/editFoodType, storeId: {}, phone: {}, newFoodTypeName: {}, oldFoodTypeName: {}", storeId, dto.getPhone(), dto.getNewFoodTypeName(), dto.getOldFoodTypeName());
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
        }
        merchantFoodManageService.editFoodTypeByStoreId(storeId, dto.getNewFoodTypeName(), dto.getOldFoodTypeName());
        return ResultGenerator.genSuccessResult();
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示删除菜品类别成功；code 为 400 时，message 字段返回错误提示信息")
    @Operation(summary = "21.10 删除菜品类别", tags = "21. 商铺端菜品管理", operationId = "21.10")
    @PostMapping("/deleteFoodType")
    public Result<Void> deleteFoodType(@Valid @RequestBody DeleteFoodTypeDTO dto) {
        String storeId = dto.getStoreId();
        log.info("/deleteFoodType, storeId: {}, phone: {}, foodTypeName: {}", storeId, dto.getPhone(), dto.getFoodTypeName());
        if (StringUtils.isBlank(storeId)) {
            // 如果前端传递过来的 storeId 为空，则根据店主手机号获取该店铺的 ID
            storeId = merchantStoreManageService.queryStoreIdByMerchantPhone(dto.getPhone());
        }
        merchantFoodManageService.deleteFoodTypeByStoreId(storeId, dto.getFoodTypeName());
        return ResultGenerator.genSuccessResult();
    }
}
